const {
  GiftShopModel
} = require('../../../../utils/giftshop-model.js');
var giftShopModel = new GiftShopModel();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    order: null, //订单信息
    isPassword: false, //支付弹出层
    shopId: '', //门店名称
    orderCode: '', //订单号
    timerName: '',
    day: '0',
    hou: '00',
    min: "00",
    sec: "00",
    orderAt: null, //创建订单时间
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      shopId: options.shopId || '', //门店名称
      orderCode: options.orderCode || '', //订单号
    }, () => {
      this.getOrderDetail();
    })
  },

  /**
   * 订单详情
   */
  getOrderDetail() {
    let that = this;
    giftShopModel.userOrderSubDetail({
      merchantId: wx.getStorageSync('merchantId'), //商户ID
      shopId: that.data.shopId, //门店id
      orderCode: that.data.orderCode //订单号
    }).then(data => {
      that.setData({
        order: data || null,
        orderAt: data.orderAt || null
      })
      if (data.orderState == 0) { //-1: 全部 0:待付款 1.待发货 2:待收货 3:已完成 4:已取消 5:退款中 6:退款成功
        that.countDown()
      }
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },

  /**
   * 取消订单
   */
  cancelOrder(e) {
    let that = this;
    let code = e.currentTarget.dataset.code //订单号
    let shopId = e.currentTarget.dataset.id //门店id
    wx.showModal({
      title: '是否取消订单？',
      cancelColor: '#333333', //取消文字的颜色
      confirmColor: '#333333', //确定文字的颜色
      confirmText: '确认',
      success(res) {
        if (res.confirm) {
          wx.reportAnalytics('gift_orderdetails_cancelorder');
          giftShopModel.userOrderCancel({
            merchantId: wx.getStorageSync('merchantId'), //商户ID
            shopId: shopId, //门店id
            orderCode: code, //订单号
          }).then(data => {
            that.setData({
              orderList: [], //订单数据
              isHints: false,
              pageCount: 0,
              loadText: ""
            }, () => {
              that.getOrderDetail();
            })
          }).catch(err => {
            wx.showToast({
              title: `${err.error}`,
              icon: 'none',
              duration: 2000
            })
          })
        } else if (res.cancel) {}
      }
    })
  },

  /**
   * 去支付
   */
  orderPay(e) {
    wx.reportAnalytics('gift_orderdetails_orderpay');
    let code = e.currentTarget.dataset.code //订单号
    let shopId = e.currentTarget.dataset.id //门店id
    this.setData({
      shopId: shopId, //门店id
      orderCode: code, //订单号
      isPassword: true
    })
  },

  /**
   * 关闭支付页面
   */
  closePay: function (e) {
    wx.reportAnalytics('gift_orderdetails_cancelpay');
    this.setData({
      isPassword: false
    })
  },

  /**
   * 
   * 支付成功
   */
  orderPaymentSuccess: function () {
    wx.reportAnalytics('gift_orderdetails_paysuccess');
    wx.redirectTo({
      url: '/pages/giftShop/payment/paymentSuccess/index?shopId=' + this.data.shopId + '&orderCode=' + this.data.orderCode
    })
  },

  /**
   * 跳转到物流信息页面
   */
  goOrderTracking: function (e) {
    wx.reportAnalytics('gift_orderdetails_logistics');
    let code = e.currentTarget.dataset.code //订单号
    let shopId = e.currentTarget.dataset.id //门店id
    wx.navigateTo({
      url: '/pages/giftShop/myOrder/orderTracking/index?orderCode=' + code + '&shopId=' + shopId
    })
  },
 /**
  * 倒计时
  * 注意！！！时间的【-】间隔符必须改成【/】不然ios不兼容
  */ 
  countDown: function () {
    var that = this;
    var nowTime = new Date().getTime(); //现在时间（时间戳）
    var endTime = new Date(that.data.orderAt.replace(/-/g, '/')).getTime() + 0.5 * 60 * 60 * 1000; //结束时间（时间戳）
    var time = (endTime - nowTime) / 1000; //距离结束的毫秒数
    let day = parseInt(time / (60 * 60 * 24));
    let hou = parseInt(time % (60 * 60 * 24) / 3600);
    let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
    let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
    day = that.timeFormin(day);
    hou = that.timeFormin(hou);
    min = that.timeFormin(min);
    sec = that.timeFormin(sec);
    that.setData({
      day: that.timeFormat(day),
      hou: that.timeFormat(hou),
      min: that.timeFormat(min),
      sec: that.timeFormat(sec)
    })
    // 每1000ms刷新一次
    if (time > 0) {
      that.setData({
        timerName: setTimeout(function () { //这里把setInterval赋值给变量名为timer的变量
          that.countDown()
        }, 1000)
      })
    } else {
      that.getOrderDetail();
      clearInterval(that.data.timerName);
    }
  },
  //小于10的格式化函数（2变成02）
  timeFormat(param) {
    return param < 10 ? '0' + param : param;
  },
  //小于0的格式化函数（不会出现负数）
  timeFormin(param) {
    return param < 0 ? 0 : param;
  },

  /**
   * 跳转到服务单详情页面
   */
  goServiceDetail: function (e) {
    wx.reportAnalytics('gift_orderdetails_servicedetail');
    let code = e.currentTarget.dataset.code //服务单号
    let shopName = e.currentTarget.dataset.name
    if (code) {
      // wx.navigateTo({
      //   url: '/pages/giftShop/serviceOrder/serviceDetails/index?orderCode=' + code + '&skuId=' + skuId + '&orderStatus=1'
      // })
      wx.navigateTo({
        url: '/pages/giftShop/serviceOrder/afterSale/index?orderCode=' + code + '&shopName=' + shopName
      })
    }
  },

  /**
   * 换货
   */
  setAfterSale: function (e) {
    wx.reportAnalytics('gift_orderdetails_exchangegoods');
    let orderCode = e.currentTarget.dataset.code
    let partnerSign = e.currentTarget.dataset.id
    let skuId = e.currentTarget.dataset.sku
    let quantity = e.currentTarget.dataset.num
    giftShopModel.serviceOrderPreCheck({
      merchantId: wx.getStorageSync('merchantId'), //商户ID
      orderCode: orderCode, //订单号
      partnerSign: partnerSign, //第三方id
      skuId: skuId, //商品sku
      quantity: quantity, //换货数量
    }).then(data => {
      wx.navigateTo({
        url: `/pages/giftShop/serviceOrder/afterType/index?currency=${JSON.stringify(data)}`
      })
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },

    /**
   * 商品详情
   */
  goDetail(e) {
    wx.reportAnalytics('gift_orderdetails_goodsdetail');
    const skuId = e.currentTarget.dataset.sku
    const item = e.currentTarget.dataset.item
    const shopInfo = wx.getStorageSync('shopInfo')
    wx.navigateTo({
      url: `/pages/giftShop/goodsDetail/index?shopId=${shopInfo.shopId}&skuId=${skuId}&channelGoodsId=${item.channelGoodsId}`
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(this.data.timerName);
    this.closePay();
  },
})